import service from 'axios'
import { handleSSO } from '@/utils/func'
import router from '@/router/index'

// 请求拦截器
service.interceptors.request.use(
  (config: any) => {
    config.headers['X-Requested-With'] = 'XMLHttpRequest'
    return config
  },
  (error: any) => {
    console.log('request:', error) // for debug
    return Promise.reject(error)
  }
)

function errorMsgTips(msg: any) {
  window.$message.error(msg)
}

// 响应拦截器
service.interceptors.response.use(
  (response: { data: any; config: any }) => {
    const resData = response.data || {}

    if (resData.code === 58302) {
      window.location.href = `https://auth.58.com/58shieldlogin.html?domain=${
        location.host
      }&req=${encodeURIComponent(location.pathname)}&protocol=https${location.hash}`
    } else if (resData.code == 0 || resData.code == 200) {
      return resData
    } else if (resData.code == 4004) {
      // 无权限
      router.push({
        path: '/notPermission'
      })
    } else {
      errorMsgTips(resData.message || '接口错误，请稍后重试')
    }
  },
  (error: any) => {
    if (service.isCancel(error)) {
      console.log('取消请求 error -> ', error)
      return
    }
    if (error && error.response && error.response.status === 302) {
      if (process.env.NODE_ENV === 'development') {
        errorMsgTips('请替换Cookies里的SSO_SESSION_ID')
        return
      } else {
        window.location.href = handleSSO('login')
      }
    } else if (error && error.stack.includes('timeout')) {
      errorMsgTips('接口超时')
      return
    } else if (error && error.stack.includes('Network')) {
      errorMsgTips('网络异常')
      return
    }
    return Promise.reject(error)
  }
)

export default service
